# -*- coding: UTF-8 -*-

from IUtils import *
from IPlatform import *
import re
import time


def Convert():
    try:
        template = IUtils.fromFile("template/index.html")
        config = IUtils.fromJsonAsDict("template/config.json")

        #video resource
        portrait = IUtils.fromFile2Base64("videos/portrait.mp4")
        landscape = IUtils.fromFile2Base64("videos/landscape.mp4")
        videoRes = f'''
            window.videos = [null, null];
            window.videos[0] = "data:video/mp4;base64,{portrait}";
            window.videos[1] = "data:video/mp4;base64,{landscape}";
        '''

        #init channel. example applovin !
        playableSDK = '''
            window.playableSDK = {};
            window.playableSDK.init=function()
            {
                window.playableSDK.storeUrl=(/android/i.test(navigator.userAgent))?window.androidStoreUrl:window.iosStoreUrl;
                window.playableSDK.install=function(){
                    window.mraid&&window.mraid.open(window.playableSDK.storeUrl);
                }
            }
        '''
        initContet = f'''
            <script type="text/javascript">
                window.androidStoreUrl="{config['androidUrl']}";
                window.iosStoreUrl="{config['iosUrl']}";
                {playableSDK}
                {videoRes}
            </script>
        '''

        #install event
        installEvent = '''
            window.playableSDK.install();
        '''

        template = re.sub( r"__initEvent",initContet,template,1 )
        template = re.sub( r"__installEvent",installEvent,template,1 )
        IUtils.writeInFile( "out/index.html", template )
    except Exception as e:
        print(e)
        Debug.LogExcept()


if __name__ == "__main__":
    s = time.time()
    print(f'Start : { time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) }')

    Convert()
    Debug.Export()

    print(f'End : { time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) }')
    print(f'Cost : { time.time() - s }')